package com.doeis.push;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.doeis.common.utils.StringUtils;
import com.doeis.jpush.DoeisJPush;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.voland.core.db.DBManager;
import com.voland.core.utils.IDGenerator;

public class BaiduServiceContext {
	
	//userid-基本信息
	public static Map<String, PushBaidu> map_userinfo = new ConcurrentHashMap <String, PushBaidu>();
	

	public static void main(String[] args) {
		initPushBaidu();
		DoeisJPush.sendNotification("402881f04e677839014e6779b57a000a","aaa");
	}
	
	public static void initPushBaidu(){
		try{
			Injector injector = Guice.createInjector();
			PushBaiduDao pushBaiduDao = injector.getInstance(PushBaiduDao.class);
			
			PushBaidu pushBaiduForm = new PushBaidu(); 
			List<PushBaidu>  list = pushBaiduDao.findSalePlanBaidu(pushBaiduForm);
			if(list!=null){
				for(PushBaidu pushBaidu:list){
					if(pushBaidu.getBelong_to()==null){
						pushBaiduDao.delete(pushBaidu);
						continue ;
					}
					map_userinfo.put(pushBaidu.getBelong_to(), pushBaidu);
				}
			}
		}catch(Exception  e){
			e.printStackTrace();
		}finally{
			DBManager.closeBindConnection(DBManager.getDefaultDataSourceName(Boolean.TRUE.booleanValue()));
		}
	}
	
	public static PushBaidu getPlanBaidu(String belong_to){
		return map_userinfo.get(belong_to);
	}
	
	
	public static boolean putPushBaidu(PushBaidu form){
		try{
			Injector injector = Guice.createInjector();
			PushBaiduDao pushBaiduDao = injector.getInstance(PushBaiduDao.class);
			
			//第一步 根据登陆A，查找是否账号A登陆过
			PushBaidu pushBaidu = map_userinfo.get(form.getBelong_to());
			if(pushBaidu==null){//账号A之前没有登陆过
				form.setId(IDGenerator.uuid());
				pushBaiduDao.insert(form);
				map_userinfo.put(form.getBelong_to(), form);
				
			}else{//账号A之前登陆过
				
				//首先删除以前登陆信息
				pushBaiduDao.delete(PushBaidu.class, "belong_to=?", form.getBelong_to());
				
				//再进行插入
				form.setId(IDGenerator.uuid());
				pushBaiduDao.insert(form);
				map_userinfo.put(form.getBelong_to(), form);
				
				//跟新极光的东西,这句话执行时间1s，是一个问题，需要修正
				DoeisJPush.updateAlias(form.getBelong_to(), form.getChannel_id(), form.getDevice_type());
			}
			
			//第二步，判断设备型号是否之前被绑定过
			String newchannel = form.getChannel_id();
			if(!StringUtils.isBlank(newchannel)){
				List<PushBaidu> listPush = pushBaiduDao.query(PushBaidu.class, 
						"select * from push_baidu where channel_id = ? ", newchannel);
				for(PushBaidu pushBaidu2 : listPush){
					if(pushBaidu2.getId().equals(form.getId())){
						continue ;
					}
					pushBaiduDao.delete(pushBaidu2);
					map_userinfo.remove(pushBaidu2.getBelong_to());
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			DBManager.closeAllBindConnection();
		}
		return true;
	}
	
}
